package org.googlecode.lightning.search.parse.parser.ms.office;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.hssf.extractor.ExcelExtractor;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.daragon.fulltext.parse.parser.SimpleDocParser;
import org.daragon.fulltext.segment.Holder;

/**
 * 
 * @author daragon
 * 
 */
public class ExcelParser extends SimpleDocParser {
	private final static Log log = LogFactory.getLog(ExcelParser.class);

	public static final String MIME_TYPE = "application/vnd.ms-excel";

	/**
	 * Extract the text from an Excel document.
	 * <p>
	 * 
	 * @param holder
	 *            The file's Content to extract text from.
	 * @return The extracted text.
	 * @throws IOException
	 */
	protected String extractText(Holder holder) {

		ByteArrayInputStream is = new ByteArrayInputStream(holder.getContent());
		ExcelExtractor extractor;
		try {
			extractor = new ExcelExtractor(new POIFSFileSystem(is));
			return extractor.getText();
		} catch (IOException e) {
			log.error("Exception while parsing file" + holder.getFilename());
		}catch(EncryptedDocumentException e){
			log.error("The document : " + holder.getFilename()
					+ " is a encrypted word files!");
		} finally {
			IOUtils.closeQuietly(is);
		}
		return null;
	}

}
